<?php
namespace My\Model;

use Utuo\UtuoModel;

class AgentModel extends UtuoModel {
	
    static $agentLevel = array(
        '0' => '一级代理商',
        '1' => '二级代理商',
        '2' => '三级代理商',
        '3' => '四级代理商',
        '4' => '五级代理商',
        '5' => '六级代理商',
        '6' => '七级代理商',
        '7' => '八级代理商',
    );
    
    static $locType = array(
        '0' => '无',
        '1' => '省代',
        '2' => '市代',
        '3' => '区代',
    );
    
    // 自动验证
    protected $_validate = array(
    	array('wechat_uid', 'getWechatUid','设置要设为代理的用户不正确', self::MUST_VALIDATE, 'callback'),
    	array('password', 'require', '密码必须', self::MUST_VALIDATE, '', self::MODEL_INSERT),
    );
    
    // 自动赋值
    protected $_auto = array(
        array('begin_time', 'strtotime', self::MODEL_BOTH, 'function'),
        array('end_time', 'strtotime', self::MODEL_BOTH, 'function'),
    	array('password', 'hash_pwd', self::MODEL_BOTH, 'function'),
    );
    
    
//     protected function _before_insert(&$data, $options) {
//     	parent::_before_insert($data, $options);
//     }
    
    /**
     * 新增代理商用户后处理
     * @see \Think\Model::_after_insert()
     */
    protected function _after_insert($data, $options) {
        $id = $data[$this->getPk()];
        if ( false !== $id ) {
        	/* 添加管理员 */
            $addData = array(
                'agent_id' => $id,
                'name' => $data['name'],
                'password' => $data['password'],
                'last_login_time' => 0,
                'last_login_ip' => '',
                'login_count' => 0,
                'is_role' => 0,
                'is_super' => 1,
            );
            $data['email'] and $addData['email'] = $data['email'];
            if ( $data['user_name'] ) {
                $addData['user_name'] = $data['user_name'];
            } else {
                $addData['user_name'] = "u".time().rand(10000, 99999);
            }
        	M("AgentAdmin")->add( $addData );
        	/* 更新关系树 */
        	$parentId = $data['parent_id']*1;
        	if ( $parentId ) {
        		$tree = M("Agent")->where('id=%d and cid=%d', $parentId, $data['cid'])->getField('tree');
        		$tree = $id.','.$tree;
        	} else {
        		$tree = $id;
        	}
        	M("Agent")->where("id=%d", $id)->setField("tree", $tree);
            /* 设置用户为代理商类型  */
            $wechatUid = $data['wechat_uid'];
            $m = M("WechatUser");
            $wechatUser = $m->where("id=%d", $wechatUid)->find();
            $userRole = new UserRole();
            $type = $userRole->type($wechatUser['type'])->becomeTo(WechatUserModel::USER_TYPE_AGENT)->getType();
            $m->where("id=%d", $wechatUid)->setField('type', $type); 
            /* 设置用户申请代理商已通过  */
            $applyId = $_REQUEST['applyId'];
            if( $applyId ) {
            	M("AgentApply")->where(array('cid' => $this->adminId, 'id' => $applyId ))->setField('status', 1);
            }
            /* 代理商低级发展高级处理 */
            $level = $data['level'];
            $parentId = $this->getNewParent($parentId, $level, $data['cid']);
            M("Agent")->where("id=%d", $id)->setField("parent_id", $parentId);
        }
    }
    
    /**
     * 更新前处理
     * @see \Utuo\UtuoModel::_before_update()
     */
    protected function _before_update(&$data, &$options) {
    	unset($data['wechat_uid']); // 指定的用户id不可修改
    	return parent::_before_update($data, $options);
    }
    
    /**
     * 用户id验证
     */
    protected function getWechatUid() {
    	$id = I('id', 0, "intval");
    	if ( !$id ) { // 添加用户时
    		$wechatUid = I('wechat_uid', 0, "intval");
    		$wechatUser = M("WechatUser")->where("id=%d", $wechatUid)->find();
    		if ( $wechatUser ) {
    			$userRole = new UserRole();
    			if ( $userRole->type($wechatUser['type'])->is(WechatUserModel::USER_TYPE_AGENT) ) {
    				$this->error['wechat_uid'] = "您选择的用户已是代理商";
    			} else {
    				return true;
    			}
    		} else {
    			$this->error['wechat_uid'] = "请先选择已绑定的微信用户";
    		}
    		return false;
    	} else { // 修改时
    		return true;
    	}
    }
    
    
    /**
     * 获得新的父级id
     * @param unknown $parentId
     */
    private function getNewParent( $nowParentId, $newLevel, $cid ) {
        /* 升为一级 */
        if ( $nowParentId ) {
            if ( $newLevel == 0 ) { // 有父级要升1级时
                return 0;
            } else {
                $parent = M("Agent")->where("cid=%d and id=%d", $cid, $nowParentId)->find();
                $parentLevel = $parent['level']*1;
                if ( $parentLevel >= $newLevel  ) { // 与当前父级同级或超越时
                    while( $parentLevel > 0 ) {
                        $parent = M("Agent")->where("cid=%d and id=%d", $cid, $parent['parent_id'])->find();
                        $parentLevel = $parent['level']*1;
                        if ( $parentLevel < $newLevel ) {
                            return $parent['id']*1;
                        }
                    }
                    return 0;
                } else {
                    return $nowParentId;
                }
            }
        }
        return 0;
    }
    
}